package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.ForwardDto;
import com.itheima.ydd.dto.TopData;
import com.itheima.ydd.entity.Config;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.ArticleService;
import com.itheima.ydd.service.ConfigService;
import com.itheima.ydd.service.UserService;
import com.itheima.ydd.service.YddUserService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台管理
 */
@RestController
@Slf4j
@RequestMapping("index")
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private YddUserService yddUserService;

    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("login")
    public ResultData login(@RequestBody User user) {
        log.info("用户信息: 邮箱:{},密码:{}", user.toString());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getLogin_name, user.getLogin_name());
        queryWrapper.eq(User::getPassword, DigestUtils.md5Hex(user.getPassword()));
        User loginUser = userService.getOne(queryWrapper);
        if (loginUser == null) {
            throw new BusinessException("登录失败!");
        }

        Map retMap = new HashMap();
        Map tokenMap = new HashMap<>();
        // 登录成功
        if (loginUser != null) {
            // 生成token信息
            String roleId = loginUser.getRole_id()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("id", loginUser.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);

        }
        return ResultData.ok("", retMap);
    }


    /**
     * 获取系统配置
     *
     * @return
     */
    @GetMapping("getConfig")
    public ResultData getConfig() {
        List<Config> list = configService.list();

        Map<String, String> map = new HashMap<>();
        for (Config config : list) {
            map.put(config.getAttr_key(), config.getAttr_value());
        }
        return ResultData.ok("", map);
    }

    /**
     * 获取用户资料
     *
     * @param
     * @return
     */
    @PostMapping("profile")
    public ResultData profile() {
        Map<String, Object> map = configService.profile();
        return ResultData.ok("", map);
    }


    @PostMapping("/logout")
    public void logout() {
        //删除用户信息
        UserHolder.remove();
    }

    /**
     * 获取主页统计参数
     */
    @GetMapping("/baseInfo")
    public ResultData baseInfo() {
        Map<String, Object> map = configService.baseInfo();
        return ResultData.ok("", map);
    }

    /**
     * 返回热门置顶文章数据(首页)
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/new")
    public ResultData topList(Integer page, Integer limit) {
        log.info("页码page:{},每页数量limit:{}", page, limit);
        TopData topData = articleService.getTopData(page, limit);
        return ResultData.ok("", topData);
    }

    /**
     * 首页和全局数据
     */
    @GetMapping("index")
    public ResultData index() {
        ForwardDto forwardDto = configService.getForwardDto();
        return ResultData.ok("", forwardDto);
    }

    /**
     * 文章列表数据
     *
     * @param page
     * @param limit
     * @param cateid
     * @return
     */
    @GetMapping("list")
    public ResultData list(Integer page, Integer limit, String cateid) {
        log.info("页码page:{},每页数量limit:{},分类id cateid{}", page, limit, cateid);
        HashMap<String, Object> map = articleService.getPageHashMap("", "", "", cateid, page, limit);
        return ResultData.ok("", map);
    }

    /***
     * Desc:手机文章列表数据
     * @param page
     * @param limit
     * @param cateid
     * @return {@link ResultData}
     * @author Cr Mr
     * @date 2022/3/3 19:58
     */

    @GetMapping("lists")
    public ResultData lists(Integer page, Integer limit, String cateid) {
        log.info("页码page:{},每页数量limit:{},分类id cateid{}", page, limit, cateid);
        HashMap<String, Object> list = articleService.getPageHashMap("", "", "", cateid, page, limit);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        return ResultData.ok("", map);
    }

    /**
     * 获取侧边最新文章
     *
     * @return
     */
    @GetMapping("hot")
    public ResultData hot() {
        log.info("获取侧边最新文章");
        HashMap<String, Object> map = articleService.getHot();
        return ResultData.ok("", map);
    }

    /**
     * 侧边推荐文章
     *
     * @return
     */
    @GetMapping("recommend")
    public ResultData recommend() {
        log.info("侧边推荐文章");
        HashMap<String, Object> map = articleService.getRecommend();
        return ResultData.ok("", map);
    }

    /***
     * Desc:  注册
     * @param yddUser
     * @return {@link ResultData}
     * @author Cr Mr
     * @date 2022/3/3 9:07
     */
    @PostMapping("reg")
    public ResultData reg(@RequestBody YddUser yddUser) {
        log.info("注册YddUser：{}", yddUser);
        //将页面提交的密码password进行md5加密处理
        yddUser.setPassword(DigestUtils.md5Hex(yddUser.getPassword()));
        yddUser.setUsername("暂无昵称");
        yddUser.setDefault_data("1");
        yddUserService.save(yddUser);
        return ResultData.ok("注册成功", "");
    }

    /***
     * Desc: 文章详情数据
     * @param
     * @return {@link ResultData}
     * @author Cr Mr
     * @date 2022/3/3 13:20
     */
    @GetMapping("/show")
    public ResultData show(@RequestParam String id) {
        log.info("文章详情数据id:{}", id);
        HashMap<String, Object> map = articleService.show(Integer.parseInt(id));
        return ResultData.ok("", map);
    }
}
